package controller

import (
	"example.com/myproject/project/global"
	"example.com/myproject/project/models"
	"example.com/myproject/project/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

/*
todolist:

	加redis
	token发给用户的同时会存在缓存里todo
	加密todo
*/
func Register(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil { //传入json格式不当，返回错误
		c.JSON(400, gin.H{"err": err.Error()})
		return
	}
	fmt.Println(user)
	if global.Db.Create(&user).Error != nil {
		c.JSON(400, gin.H{"err": "DataBase Error"})
		return
	}

	token, _ := utils.GenerateJWT(user.Username)
	c.JSON(http.StatusOK, gin.H{"err": "0", "token": token})
}

func Login(c *gin.Context) {
	var input struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user models.User

	if err := global.Db.Where("username = ?", input.Username).First(&user).Error; err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong password"})
		return
	}
	if input.Password != user.Password {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong password"})
	}
	fmt.Println("login user.id:", user.ID)
	//根据不同的UserType创建不同的JWT，todo
	token, _ := utils.GenerateJWT(user.Username)

	var orders []models.OrderInfo
	err := models.GetOrderById(user.ID, &orders)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": "0", "token": token, "orderinfo": orders})
}
